package com.hgj.blindbox.service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hgj.blindbox.entity.BoxItem;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class BlindBoxStockService {
    private static final String BOX_STOCKS_KEY = "blindbox:stocks:";
    private static final String BOX_ITEMS_KEY = "blindbox:items:";

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取盲盒库存详情
     * @param boxId 盲盒ID
     * @return 库存详情
     */
    public Map<String, Object> getStockDetails(String boxId) {
        Map<String, Object> result = new LinkedHashMap<>();

        // 获取库存数据
        Map<Object, Object> stockMap = redisTemplate.opsForHash()
                .entries(BOX_STOCKS_KEY + boxId);

        // 计算总库存
        int totalStock = stockMap.values().stream()
                .mapToInt(value -> Integer.parseInt(value.toString()))
                .sum();
        result.put("totalStock", totalStock);

        // 获取奖品详情
        List<Map<String, Object>> prizeDetails = new ArrayList<>();
        for (Object prizeId : stockMap.keySet()) {
            Object itemJson = redisTemplate.opsForHash()
                    .get(BOX_ITEMS_KEY + boxId, prizeId.toString());

            if (itemJson != null) {
                try {
                    BoxItem item = JSONObject.parseObject(itemJson.toString(),BoxItem.class);
                    Map<String, Object> prizeInfo = new LinkedHashMap<>();
                    prizeInfo.put("id", item.getId());
                    prizeInfo.put("name", item.getName());
                    prizeInfo.put("weight", item.getWeight());
                    prizeInfo.put("initialStock", item.getStock());
                    prizeInfo.put("currentStock", Integer.parseInt(stockMap.get(prizeId).toString()));

                    prizeDetails.add(prizeInfo);
                } catch (Exception e) {
                    // 忽略解析错误的奖品
                }
            }
        }

        result.put("prizes", prizeDetails);
        return result;
    }

    /**
     * 调整奖品库存
     * @param boxId 盲盒ID
     * @param prizeId 奖品ID
     * @param delta 库存变化量
     */
    public void adjustStock(String boxId, String prizeId, int delta) {
        String stockKey = BOX_STOCKS_KEY + boxId;
        Long currentStock = redisTemplate.opsForHash().increment(stockKey, prizeId, delta);

        if (currentStock != null && currentStock < 0) {
            // 库存不足时回滚
            redisTemplate.opsForHash().increment(stockKey, prizeId, -delta);
            throw new IllegalStateException("库存不足，调整失败");
        }
    }
}
